<template>
    <div>
        <!-- 查询区域 -->
        <div class="card query-card">
            <el-input
                    v-model="data.title"
                    placeholder="请输入文章标题"
                    :prefix-icon="Search"
                    class="input-field"
            />
            <el-input
                    v-model="data.content"
                    placeholder="请输入文章内容"
                    :prefix-icon="Search"
                    class="input-field"
            />
            <el-button type="primary" @click="fetchData">查 询</el-button>
        </div>
        <!-- 操作按钮区域 -->
        <div class="card action-card">
            <el-button type="danger" @click="deleteSelectedNotices">批量删除</el-button>
            <el-button type="primary" @click="router.push('/add_article')">新 增</el-button>
        </div>
        <!-- 表格区域 -->
        <div class="card table-card">
            <el-table
                    v-loading="loading"
                    table-layout="auto"
                    :data="data.articleFormList"
                    style="width: 100%"
                    :header-cell-style="{ color: '#333', backgroundColor: '#eaf4ff' }"
                    @selection-change="handleSelectionChange"
            >
                <!--                <el-table-column type="selection" width="55"/>-->
                <el-table-column prop="title" label="文章标题"/>
                <el-table-column prop="category" label="分类标题"/>
                <el-table-column prop="tags" label="标签">
                    <template #default="scope">
                        {{ scope.row.tags }}
                    </template>
                </el-table-column>
                <el-table-column prop="userId" label="作者"/>
                <el-table-column prop="content" label="文章内容">
                    <template #default="scope">
                        <el-button type="success" @click="viewInit(scope.row.content,scope.row.title)">查看内容
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="发布时间">
                    <template #default="scope">
                        {{ formattedPublishTime(scope.row.createTime) || '--------' }}
                    </template>
                </el-table-column>
                <el-table-column prop="updateTime" label="修改时间">
                    <template #default="scope">
                        {{ formattedPublishTime(scope.row.updateTime) || '--------' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-space>
                            <el-button
                                    v-if="scope.row.reviewStatus!==PIC_REVIEW_STATUS_ENUM.PASS"
                                    type="primary"
                                    link
                                    @click="handleReview(scope.row,PIC_REVIEW_STATUS_ENUM.PASS)"
                            >
                                通过
                            </el-button>
                            <el-button
                                    v-if="scope.row.reviewStatus!==PIC_REVIEW_STATUS_ENUM.REJECT"
                                    type="danger"
                                    link
                                    @click="handleReview(scope.row,PIC_REVIEW_STATUS_ENUM.REJECT)"
                            >
                                拒绝
                            </el-button>
                            <el-button type="primary" link @click="doEdit(scope.row.id)">编辑</el-button>
                            <el-button type="danger" link @click="deleteNotice(scope.row.id)">删除</el-button>
                        </el-space>

                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-dialog
            :title="data.viewTitle"
            width="1000"
            v-model="data.viewVisible"
        >
            <MdPreview id="preview-only" :modelValue="data.viewContent"/>
        </el-dialog>

        <!-- 分页区域 -->
            <div class="card pagination-card">
                <el-pagination
                    v-model:current-page="data.currentPage"
                    v-model:page-size="data.pageSize"
                    layout="prev, pager, next"
                    :total="total"
                    :current-change="handleCurrentChange"
                />
            </div>
    </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {Search} from "@element-plus/icons-vue";
import {useRouter} from "vue-router";
import myAxios from "@/axios/axios.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {formattedPublishTime} from "@/tools/date.js";
import {PIC_REVIEW_STATUS_ENUM} from "@/constants/article.js";
import {MdPreview} from "md-editor-v3";
import {useLoginUserStore} from "@/stores/useLoginUserStore.js"; // 引入 css
// 加载状态
const loading = ref(true);
const formRef = ref();
// 路由实例
const router = useRouter();
// 获取本地存储的用户信息
const user = useLoginUserStore().loginUser;
const total = ref(0)
// 表格数据及分页信息
const data = reactive({
    title: "",
    content: "",
    coverUrl: "",
    publishTime: '',
    updateTime: '',
    pageNum: 1,
    pageSize: 100,
    currentPage: 1,
    articleFormList: [],
    form: {},
    tagList: [],
    selectedUsers: [],
    categoryList: [],
    viewContent: '',
    viewVisible: false,
    viewTitle: ''
});
const handleCurrentChange = (val) => {
    console.log(`current page: ${val}`)
    data.pageNum=val;
    fetchData();
}
// 加载表格数据
const fetchData = async () => {
    try {
        const res = await myAxios.get("/article/list/page", {
            params: {
                title: data.title,
                content: data.content,
                pageNum: data.pageNum,
                pageSize: data.pageSize,
            },
        });
        if (res.code === 0 && res.data) {
            data.articleFormList = res.data.records;
            total.value = res.data.total;
        } else {
            ElMessage.error("数据加载失败");
        }
    } catch (error) {
        ElMessage.error("网络请求出错，请稍后重试");
        console.error("数据加载出错:", error);
    } finally {
        loading.value = false;
    }
};
const viewInit = (content, title) => {
    data.viewTitle = title
    data.viewContent = content
    data.viewVisible = true
}

// 处理表格选择变化
const handleSelectionChange = (val) => {
    data.selectedUsers = val;
    console.log(val);
};

const doEdit = (id) => {
    router.push('/add_article?id=' + id)
}


// 删除文章
const deleteNotice = async (id) => {
    try {
        await ElMessageBox.confirm(
            '此操作将永久删除该文章, 是否继续?',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        const res = await myAxios.delete(`/article/delete/${id}`);
        if (res.code === 0) {
            ElMessage.success("文章删除成功");
            await load();
        } else {
            ElMessage.error("文章删除失败");
        }
    } catch (error) {
        // 判断是否是用户取消操作
        if (error === 'cancel') {
            // 用户点击了“取消”，不显示错误提示
            return;
        }
        ElMessage.error("网络请求出错，请稍后重试");
        console.error("文章删除出错:", error);
    }
};

// 批量删除文章
const deleteSelectedNotices = async () => {
    if (data.selectedUsers.length === 0) {
        ElMessage.warning("请选择要删除的文章");
        return;
    }
    try {
        const ids = data.selectedUsers.map(user => user.id);
        const res = await myAxios.post("/article/batchDelete", {ids});
        if (res.code === 0) {
            ElMessage.success("文章批量删除成功");
            await load();
        } else {
            ElMessage.error("文章批量删除失败");
        }
    } catch (error) {
        ElMessage.error("网络请求出错，请稍后重试");
        console.error("文章批量删除出错:", error);
    }
};

const handleReview = async (article, reviewStatus) => {
    const reviewMessage = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '管理员操作通过' : '管理员操作拒绝'
    const res = await myAxios.post("/article/review", {
        id: article.id,
        reviewStatus,
        reviewMessage,
    })
    if (res.code === 0) {
        ElMessage.success('审核操作成功')
        // 重新获取列表
        await fetchData()
    } else {
        ElMessage.error('审核操作失败，' + res.data.message)
    }

}
// 组件挂载时加载数据
onMounted(() => {
    fetchData()
});
</script>

<style scoped>
.card {
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 5px;
}

.query-card {
    display: flex;
    align-items: center;
}

.input-field {
    width: 240px;
    margin-right: 10px;
}

.action-card {
    display: flex;
    align-items: center;
}

.demo-drawer__content {
    padding: 20px;
}

:deep(.el-table__header th) {
    text-align: center;
}
</style>
